package com.mall.controller;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.github.pagehelper.PageHelper;
import com.mall.common.api.Code;
import com.mall.common.api.Result;
import com.mall.dto.*;
import com.mall.entity.*;
import com.mall.common.api.CommonPage;
import com.mall.common.api.CommonResult;
import com.mall.dto.*;
import com.mall.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author zzx
 * @since 2022-06-15
 */
@RestController
@Api(tags = "OmsOrderController", description = "订单管理")
@RequestMapping("/order")
public class OmsOrderController {
    @Autowired
    private OmsOrderService orderService;

    @Resource
    private OmsOrderItemService orderItemService;

    @Resource
    private SmsCouponHistoryService couponHistoryService;

    @Resource
    private SmsCouponService smsCouponService;
    
    @Resource
    private OmsCartItemService cartItemService;

    @ApiOperation(value = "新增或修改订单")
    @PostMapping("/save")
    public Result save(@RequestBody OmsOrder order) {
        //1.将订单修改内容写入表中
        boolean flag = orderService.Save(order);
        //2.将已使用优惠券状态设置为已使用,并将使用时间，订单id和订单sn写入
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = formatter.format(date);
        if(order.getCouponId()!=null)
        {
            boolean flag1= couponHistoryService.setUsed(order.getCouponId(),order.getMemberId());
            SmsCouponHistory history = couponHistoryService.getByIds(order.getMemberId(),order.getCouponId());
            SmsCoupon coupon = smsCouponService.getById(order.getCouponId());
            coupon.setUseCount(coupon.getCount()+1);
            smsCouponService.save(coupon);
            history.setOrderSn(order.getOrderSn());
            history.setUseTime(time);
            history.setOrderId(order.getId());
            couponHistoryService.save(history);

        }

        //3.将加入订单中的购物车条目从购物车中删除
        List<OmsOrderItem> list = orderItemService.getOrderItems(order.getId());
        for(int i=0;i<list.size();i++)
        {
            cartItemService.removeUsed(order.getMemberId(), list.get(i).getProductId());
        }
        return new Result(flag? Code.SAVE_OK: Code.SAVE_ERR,flag);
    }

    @ApiOperation(value = "新增直接购买订单")
    @PostMapping("/buy")
    public Result buy(@RequestBody OmsOrder order) {
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String orderSn = formatter.format(date);
        Random random = new Random();
        String time = formatter.format(date);
        for(int i=0;i<10;i++)
        {
            orderSn +=  String.valueOf(random.nextInt(10));
        }
        order.setOrderSn(orderSn);
        order.setCreateTime(date);
        if(order.getCouponId()!=null)
        {
            boolean flag1= couponHistoryService.setUsed(order.getCouponId(),order.getMemberId());
            SmsCouponHistory history = couponHistoryService.getByIds(order.getMemberId(),order.getCouponId());
            SmsCoupon coupon = smsCouponService.getById(order.getCouponId());
            coupon.setUseCount(coupon.getCount()+1);
            smsCouponService.save(coupon);
            history.setOrderSn(order.getOrderSn());
            history.setUseTime(time);
            history.setOrderId(order.getId());
            couponHistoryService.save(history);

        }
        //1.将订单修改内容写入表中
        boolean flag = orderService.Save(order);
        Long orderId =  orderService.getMax();
        Integer code = orderId !=null ? Code.GET_OK:Code.GET_ERR;
        String msg = orderId !=null ? "successful":"failed,please try again";
        return new Result(orderId,code,msg);
    }

    @ApiOperation(value = "新增订单条目")
    @PostMapping("/addOrderItem")
    public Result addOrderItem(@RequestBody OmsOrderItem omsOrderItem) {
        OmsOrder order = orderService.getById(omsOrderItem.getOrderId());
        cartItemService.removeUsed(order.getMemberId(),omsOrderItem.getProductId());
        omsOrderItem.setOrderSn(order.getOrderSn());
        boolean flag = orderItemService.save(omsOrderItem);
        return new Result(flag?Code.SAVE_OK: Code.SAVE_ERR,flag);
    }

    @ApiOperation("查询订单")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<CommonPage<OmsOrder>> list(OmsOrderQueryParam queryParam,
                                                   @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                                   @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        List<OmsOrder> orderList = orderService.list(queryParam, pageSize, pageNum);
        return CommonResult.success(CommonPage.restPage(orderList));
    }

    @ApiOperation("批量发货")
    @RequestMapping(value = "/update/delivery", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult delivery(@RequestBody List<OmsOrderDeliveryParam> deliveryParamList) {
        int count = orderService.delivery(deliveryParamList);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("批量关闭订单")
    @RequestMapping(value = "/update/close", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult close(@RequestParam("ids") List<Long> ids, @RequestParam String note) {
        int count = orderService.close(ids, note);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("批量删除订单")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult delete(@RequestParam("ids") List<Long> ids) {
        int count = orderService.delete(ids);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("获取订单详情：订单信息、商品信息、操作记录")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<OmsOrderDetail> detail(@PathVariable Long id) {
        OmsOrderDetail orderDetailResult = orderService.detail(id);
        return CommonResult.success(orderDetailResult);
    }

    @ApiOperation("修改收货人信息")
    @RequestMapping(value = "/update/receiverInfo", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updateReceiverInfo(@RequestBody OmsReceiverInfoParam receiverInfoParam) {
        int count = orderService.updateReceiverInfo(receiverInfoParam);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("修改订单费用信息")
    @RequestMapping(value = "/update/moneyInfo", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updateReceiverInfo(@RequestBody OmsMoneyInfoParam moneyInfoParam) {
        int count = orderService.updateMoneyInfo(moneyInfoParam);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("备注订单")
    @RequestMapping(value = "/update/note", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updateNote(@RequestParam("id") Long id,
                                   @RequestParam("note") String note,
                                   @RequestParam("status") Integer status) {
        int count = orderService.updateNote(id, note, status);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("查询个人订单")
    @RequestMapping(value = "/getOrderByMemberId", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<CommonPage<FrontOrderDto>> getOrderByMemberId(@RequestParam("id") Long id,
                                 @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                 @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        System.out.println("pageSize:"+pageSize);
        System.out.println("pageNum:"+pageNum);

        List<FrontOrderDto> orderList = orderService.getOrderByMemberId(id, pageSize, pageNum);
        return CommonResult.success(CommonPage.restPage(orderList));
    }


    @ApiOperation("根据订单id查询订单")
    @GetMapping("/getById/{id}")
    public CommonResult getById(@PathVariable("id") Long orderId){
        return CommonResult.success(orderService.getById(orderId));
    }


    @ApiOperation("根据订单id查询订单条目")
    @GetMapping("/getOrderItems/{id}")
    public CommonResult getOrderItems(@PathVariable("id") Long orderId) {
        return CommonResult.success(orderItemService.getOrderItems(orderId));
    }

    @ApiOperation("确认收货")
    @RequestMapping(value = "/confirm/{id}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult updateNote(@PathVariable("id") Long id) {
        int count = orderService.confirm(id);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("支付接口")
    @RequestMapping(value = "/pay", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult pay(@RequestParam(value = "orderId") Long orderId,
                            @RequestParam(value = "payType") int payType) {
        int count = orderService.pay(orderId, payType);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }
}
